// 初始化 Mermaid
mermaid.initialize({
    startOnLoad: false,
    theme: 'default',
    securityLevel: 'loose',
    fontFamily: 'inherit',
    fontSize: '16px'
});

// 全局变量
let currentZoom = 1;
let debounceTimer = null;
let diagramId = 0;
let isDragging = false;
let dragStartX = 0;
let dragStartY = 0;
let translateX = 0;
let translateY = 0;
let currentChartId = null;
let currentChartName = '未命名图表';

// DOM 元素
const mermaidInput = document.getElementById('mermaid-input');
const previewContent = document.getElementById('preview-content');
const zoomLevel = document.getElementById('zoom-level');
const exportSvgBtn = document.getElementById('export-svg');
const exportPngBtn = document.getElementById('export-png');
const statusText = document.getElementById('status-text');
const charCount = document.getElementById('char-count');
const resizer = document.getElementById('resizer');

// 图表管理元素
const newChartBtn = document.getElementById('new-chart');
const saveChartBtn = document.getElementById('save-chart');
const loadChartBtn = document.getElementById('load-chart');
const currentChartSpan = document.getElementById('current-chart');

// 模态框元素
const saveModal = document.getElementById('save-modal');
const loadModal = document.getElementById('load-modal');
const saveClose = document.getElementById('save-close');
const loadClose = document.getElementById('load-close');
const chartNameInput = document.getElementById('chart-name');
const saveConfirmBtn = document.getElementById('save-confirm');
const saveCancelBtn = document.getElementById('save-cancel');
const chartList = document.getElementById('chart-list');

// 本地存储键名
const STORAGE_KEY = 'mermaid_charts';
const LAST_CHART_KEY = 'mermaid_last_chart';

// 图表数据管理类
class ChartManager {
    constructor() {
        this.charts = this.loadCharts();
    }

    // 从localStorage加载图表
    loadCharts() {
        try {
            const data = localStorage.getItem(STORAGE_KEY);
            return data ? JSON.parse(data) : {};
        } catch (error) {
            console.error('加载图表失败:', error);
            return {};
        }
    }

    // 保存图表到localStorage
    saveCharts() {
        try {
            localStorage.setItem(STORAGE_KEY, JSON.stringify(this.charts));
        } catch (error) {
            console.error('保存图表失败:', error);
            alert('保存失败，可能是存储空间不足');
        }
    }

    // 保存当前编辑的图表
    saveLastChart() {
        try {
            const lastChart = {
                id: currentChartId,
                name: currentChartName,
                content: mermaidInput.value,
                timestamp: Date.now()
            };
            localStorage.setItem(LAST_CHART_KEY, JSON.stringify(lastChart));
        } catch (error) {
            console.error('保存最后编辑的图表失败:', error);
        }
    }

    // 加载最后编辑的图表
    loadLastChart() {
        try {
            const data = localStorage.getItem(LAST_CHART_KEY);
            if (data) {
                const lastChart = JSON.parse(data);
                mermaidInput.value = lastChart.content;
                currentChartId = lastChart.id;
                currentChartName = lastChart.name;
                updateCurrentChartDisplay();
                return true;
            }
        } catch (error) {
            console.error('加载最后编辑的图表失败:', error);
        }
        return false;
    }

    // 添加新图表
    addChart(name, content) {
        const id = Date.now().toString();
        this.charts[id] = {
            id,
            name,
            content,
            created: new Date().toLocaleString(),
            updated: new Date().toLocaleString()
        };
        this.saveCharts();
        return id;
    }

    // 更新图表
    updateChart(id, name, content) {
        if (this.charts[id]) {
            this.charts[id].name = name;
            this.charts[id].content = content;
            this.charts[id].updated = new Date().toLocaleString();
            this.saveCharts();
            return true;
        }
        return false;
    }

    // 删除图表
    deleteChart(id) {
        if (this.charts[id]) {
            delete this.charts[id];
            this.saveCharts();
            return true;
        }
        return false;
    }

    // 获取图表
    getChart(id) {
        return this.charts[id] || null;
    }

    // 获取所有图表
    getAllCharts() {
        return Object.values(this.charts).sort((a, b) => 
            new Date(b.updated) - new Date(a.updated)
        );
    }
}

// 初始化图表管理器
const chartManager = new ChartManager();

// 更新当前图表显示
function updateCurrentChartDisplay() {
    const hasChanges = hasUnsavedChanges();
    const displayName = hasChanges ? `${currentChartName} *` : currentChartName;
    currentChartSpan.textContent = displayName;
    currentChartSpan.style.color = hasChanges ? '#e74c3c' : '#7f8c8d';
}

// 渲染图表
async function renderDiagram() {
    const code = mermaidInput.value.trim();
    if (!code) {
        previewContent.innerHTML = '<div class="loading">请输入 Mermaid 代码</div>';
        return;
    }

    try {
        statusText.textContent = '正在渲染...';
        previewContent.innerHTML = '<div class="loading">正在生成图表...</div>';

        // 验证语法
        const isValid = await mermaid.parse(code);
        if (!isValid) {
            throw new Error('语法错误');
        }

        // 生成唯一ID
        const id = `mermaid-diagram-${++diagramId}`;
        
        // 渲染图表
        const { svg } = await mermaid.render(id, code);
        
        // 创建预览容器
        const wrapper = document.createElement('div');
        wrapper.className = 'preview-wrapper';
        wrapper.innerHTML = svg;
        
        // 更新预览
        previewContent.innerHTML = '';
        previewContent.appendChild(wrapper);
        
        // 重置位置和缩放
        translateX = 0;
        translateY = 0;
        currentZoom = 1;
        
        // 应用变换
        applyTransform();
        
        statusText.textContent = '渲染完成';

        // 保存当前状态
        chartManager.saveLastChart();
    } catch (error) {
        console.error('渲染错误:', error);
        previewContent.innerHTML = `<div class="error-message">图表渲染失败:\n${error.message}</div>`;
        statusText.textContent = '渲染失败';
    }
}

// 防抖渲染
function debounceRender() {
    clearTimeout(debounceTimer);
    debounceTimer = setTimeout(renderDiagram, 500);
}

// 应用变换
function applyTransform() {
    const wrapper = previewContent.querySelector('.preview-wrapper');
    if (wrapper) {
        wrapper.style.transform = `translate(calc(-50% + ${translateX}px), calc(-50% + ${translateY}px)) scale(${currentZoom})`;
        zoomLevel.textContent = `${Math.round(currentZoom * 100)}%`;
    }
}

// 滚轮缩放
function handleWheel(e) {
    e.preventDefault();
    
    const wrapper = previewContent.querySelector('.preview-wrapper');
    if (!wrapper) return;

    // 计算鼠标相对于容器的位置
    const rect = previewContent.getBoundingClientRect();
    const mouseX = e.clientX - rect.left;
    const mouseY = e.clientY - rect.top;
    
    // 计算鼠标相对于图表中心的偏移
    const centerX = rect.width / 2;
    const centerY = rect.height / 2;
    const offsetX = mouseX - centerX - translateX;
    const offsetY = mouseY - centerY - translateY;

    const oldZoom = currentZoom;
    const zoomFactor = e.deltaY > 0 ? 0.9 : 1.1;
    currentZoom = Math.min(Math.max(currentZoom * zoomFactor, 0.1), 10);
    
    // 调整平移量，使缩放以鼠标位置为中心
    const zoomDelta = currentZoom / oldZoom;
    translateX -= offsetX * (zoomDelta - 1);
    translateY -= offsetY * (zoomDelta - 1);
    
    applyTransform();
}

// 拖拽功能
function handleMouseDown(e) {
    const wrapper = previewContent.querySelector('.preview-wrapper');
    if (!wrapper) return;
    
    isDragging = true;
    dragStartX = e.clientX;
    dragStartY = e.clientY;
    
    e.preventDefault();
}

function handleMouseMove(e) {
    if (!isDragging) return;
    
    const deltaX = e.clientX - dragStartX;
    const deltaY = e.clientY - dragStartY;
    
    translateX += deltaX;
    translateY += deltaY;
    
    dragStartX = e.clientX;
    dragStartY = e.clientY;
    
    applyTransform();
}

function handleMouseUp() {
    isDragging = false;
}

// 导出功能
function exportSvg() {
    const svg = previewContent.querySelector('svg');
    if (!svg) {
        alert('没有可导出的图表');
        return;
    }

    const svgData = new XMLSerializer().serializeToString(svg);
    const blob = new Blob([svgData], { type: 'image/svg+xml' });
    const url = URL.createObjectURL(blob);
    
    const a = document.createElement('a');
    a.href = url;
    a.download = `${currentChartName}-${Date.now()}.svg`;
    a.click();
    
    URL.revokeObjectURL(url);
}

function exportPng() {
    const svg = previewContent.querySelector('svg');
    if (!svg) {
        alert('没有可导出的图表');
        return;
    }

    const svgData = new XMLSerializer().serializeToString(svg);
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');
    const img = new Image();
    
    img.onload = function() {
        canvas.width = img.width;
        canvas.height = img.height;
        ctx.fillStyle = 'white';
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        ctx.drawImage(img, 0, 0);
        
        canvas.toBlob(function(blob) {
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `${currentChartName}-${Date.now()}.png`;
            a.click();
            URL.revokeObjectURL(url);
        }, 'image/png');
    };
    
    img.src = 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(svgData)));
}

// 更新字符计数
function updateCharCount() {
    const count = mermaidInput.value.length;
    charCount.textContent = `${count} 字符`;
}

// 检查是否有未保存的更改
function hasUnsavedChanges() {
    const currentContent = mermaidInput.value.trim();
    
    // 如果没有内容，则没有未保存的更改
    if (!currentContent) {
        return false;
    }
    
    // 如果是新图表（没有ID），则有未保存的更改
    if (!currentChartId) {
        return true;
    }
    
    // 检查当前内容是否与保存的内容一致
    const savedChart = chartManager.getChart(currentChartId);
    if (!savedChart) {
        return true;
    }
    
    return currentContent !== savedChart.content.trim();
}

// 新建图表
function newChart() {
    if (hasUnsavedChanges()) {
        if (confirm('当前图表有未保存的更改，确定要新建图表吗？')) {
            createNewChart();
        }
    } else {
        createNewChart();
    }
}

function createNewChart() {
    mermaidInput.value = `graph TD
    A[开始] --> B{条件判断}
    B -->|是| C[执行A]
    B -->|否| D[执行B]
    C --> E[结束]
    D --> E
    
    style A fill:#e1f5fe
    style E fill:#ffebee`;
    
    currentChartId = null;
    currentChartName = '未命名图表';
    updateCurrentChartDisplay();
    updateCharCount();
    renderDiagram();
}

// 保存图表
function saveChart() {
    const content = mermaidInput.value.trim();
    if (!content) {
        alert('请输入图表内容');
        return;
    }
    
    chartNameInput.value = currentChartName === '未命名图表' ? '' : currentChartName;
    saveModal.style.display = 'block';
    chartNameInput.focus();
}

function confirmSave() {
    const name = chartNameInput.value.trim();
    if (!name) {
        alert('请输入图表名称');
        return;
    }
    
    const content = mermaidInput.value.trim();
    
    if (currentChartId) {
        // 更新现有图表
        chartManager.updateChart(currentChartId, name, content);
    } else {
        // 创建新图表
        currentChartId = chartManager.addChart(name, content);
    }
    
    currentChartName = name;
    updateCurrentChartDisplay();
    closeModal(saveModal);
    statusText.textContent = '图表已保存';
    
    setTimeout(() => {
        statusText.textContent = '就绪';
    }, 2000);
}

// 加载图表
function loadChart() {
    loadModal.style.display = 'block';
    renderChartList();
}

function renderChartList() {
    const charts = chartManager.getAllCharts();
    
    if (charts.length === 0) {
        chartList.innerHTML = '<div class="empty-message">暂无保存的图表</div>';
        return;
    }
    
    chartList.innerHTML = charts.map(chart => `
        <div class="chart-item">
            <div class="chart-info">
                <div class="chart-name">${escapeHtml(chart.name)}</div>
                <div class="chart-date">创建：${chart.created} | 更新：${chart.updated}</div>
            </div>
            <div class="chart-actions">
                <button class="btn btn-primary btn-small" onclick="loadChartById('${chart.id}')">加载</button>
                <button class="btn btn-danger btn-small" onclick="deleteChartById('${chart.id}')">删除</button>
            </div>
        </div>
    `).join('');
}

function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

function loadChartById(id) {
    const chart = chartManager.getChart(id);
    if (chart) {
        mermaidInput.value = chart.content;
        currentChartId = chart.id;
        currentChartName = chart.name;
        updateCurrentChartDisplay();
        updateCharCount();
        renderDiagram();
        closeModal(loadModal);
        statusText.textContent = '图表已加载';
        
        setTimeout(() => {
            statusText.textContent = '就绪';
        }, 2000);
    }
}

function deleteChartById(id) {
    const chart = chartManager.getChart(id);
    if (chart && confirm(`确定要删除图表"${chart.name}"吗？`)) {
        chartManager.deleteChart(id);
        renderChartList();
        
        // 如果删除的是当前图表，重置状态
        if (currentChartId === id) {
            currentChartId = null;
            currentChartName = '未命名图表';
            updateCurrentChartDisplay();
        }
    }
}

// 模态框控制
function closeModal(modal) {
    modal.style.display = 'none';
}

// 面板大小调整
let isResizing = false;
let startX = 0;
let startY = 0;
let startLeftWidth = 0;
let startTopHeight = 0;

// 检测是否为移动端布局
function isMobileLayout() {
    const isMobile = window.innerWidth <= 768;
    console.log('Screen width:', window.innerWidth, 'Is mobile:', isMobile);
    return isMobile;
}

resizer.addEventListener('mousedown', function(e) {
    isResizing = true;
    startX = e.clientX;
    startY = e.clientY;
    startLeftWidth = document.querySelector('.editor-panel').offsetWidth;
    startTopHeight = document.querySelector('.editor-panel').offsetHeight;
    document.addEventListener('mousemove', handleResizeMouseMove);
    document.addEventListener('mouseup', handleResizeMouseUp);
    e.preventDefault();
});

// 添加触摸事件支持
resizer.addEventListener('touchstart', function(e) {
    isResizing = true;
    const touch = e.touches[0];
    startX = touch.clientX;
    startY = touch.clientY;
    startLeftWidth = document.querySelector('.editor-panel').offsetWidth;
    startTopHeight = document.querySelector('.editor-panel').offsetHeight;
    document.addEventListener('touchmove', handleResizeTouchMove);
    document.addEventListener('touchend', handleResizeTouchEnd);
    e.preventDefault();
});

function handleResizeMouseMove(e) {
    if (!isResizing) return;
    
    if (isMobileLayout()) {
        // 移动端垂直调整
        const deltaY = e.clientY - startY;
        const newTopHeight = startTopHeight + deltaY;
        const containerHeight = document.querySelector('.container').offsetHeight;
        const minHeight = 150;
        const maxHeight = containerHeight - minHeight - 4;
        
        if (newTopHeight >= minHeight && newTopHeight <= maxHeight) {
            const topPercent = (newTopHeight / containerHeight) * 100;
            const bottomPercent = 100 - topPercent;
            
            const editorPanel = document.querySelector('.editor-panel');
            const previewPanel = document.querySelector('.preview-panel');
            
            // 确保宽度为100%（移动端）
            editorPanel.style.width = '100%';
            previewPanel.style.width = '100%';
            editorPanel.style.height = `${topPercent}%`;
            previewPanel.style.height = `${bottomPercent}%`;
        }
    } else {
        // 桌面端水平调整
        const deltaX = e.clientX - startX;
        const newLeftWidth = startLeftWidth + deltaX;
        const containerWidth = document.querySelector('.container').offsetWidth;
        const minWidth = 200;
        const maxWidth = containerWidth - minWidth - 4;
        
        if (newLeftWidth >= minWidth && newLeftWidth <= maxWidth) {
            const leftPercent = (newLeftWidth / containerWidth) * 100;
            const rightPercent = 100 - leftPercent;
            
            document.querySelector('.editor-panel').style.width = `${leftPercent}%`;
            document.querySelector('.preview-panel').style.width = `${rightPercent}%`;
        }
    }
}

function handleResizeTouchMove(e) {
    if (!isResizing) return;
    const touch = e.touches[0];
    
    if (isMobileLayout()) {
        // 移动端垂直调整
        const deltaY = touch.clientY - startY;
        const newTopHeight = startTopHeight + deltaY;
        const containerHeight = document.querySelector('.container').offsetHeight;
        const minHeight = 150;
        const maxHeight = containerHeight - minHeight - 4;
        
        if (newTopHeight >= minHeight && newTopHeight <= maxHeight) {
            const topPercent = (newTopHeight / containerHeight) * 100;
            const bottomPercent = 100 - topPercent;
            
            const editorPanel = document.querySelector('.editor-panel');
            const previewPanel = document.querySelector('.preview-panel');
            
            // 确保宽度为100%（移动端）
            editorPanel.style.width = '100%';
            previewPanel.style.width = '100%';
            editorPanel.style.height = `${topPercent}%`;
            previewPanel.style.height = `${bottomPercent}%`;
        }
    }
    e.preventDefault();
}

function handleResizeMouseUp() {
    isResizing = false;
    document.removeEventListener('mousemove', handleResizeMouseMove);
    document.removeEventListener('mouseup', handleResizeMouseUp);
}

function handleResizeTouchEnd() {
    isResizing = false;
    document.removeEventListener('touchmove', handleResizeTouchMove);
    document.removeEventListener('touchend', handleResizeTouchEnd);
}

// 监听窗口大小变化，重置面板尺寸
function resetPanelSizes() {
    const editorPanel = document.querySelector('.editor-panel');
    const previewPanel = document.querySelector('.preview-panel');
    
    console.log('resetPanelSizes called');
    
    if (isMobileLayout()) {
        console.log('Setting mobile layout - clearing inline styles');
        // 移动端：清除内联样式，让CSS媒体查询生效
        editorPanel.style.width = '';
        previewPanel.style.width = '';
        editorPanel.style.height = '';
        previewPanel.style.height = '';
    } else {
        console.log('Setting desktop layout');
        // 桌面端：设置默认的左右布局尺寸
        editorPanel.style.width = '30%';
        previewPanel.style.width = '70%';
        editorPanel.style.height = '';
        previewPanel.style.height = '';
    }
}

// 窗口大小变化时重置布局
window.addEventListener('resize', function() {
    resetPanelSizes();
});

// 事件监听
mermaidInput.addEventListener('input', function() {
    updateCharCount();
    updateCurrentChartDisplay();
    debounceRender();
});

// 图表管理按钮事件
newChartBtn.addEventListener('click', newChart);
saveChartBtn.addEventListener('click', saveChart);
loadChartBtn.addEventListener('click', loadChart);

// 导出按钮事件
exportSvgBtn.addEventListener('click', exportSvg);
exportPngBtn.addEventListener('click', exportPng);

// 模态框事件
saveClose.addEventListener('click', () => closeModal(saveModal));
loadClose.addEventListener('click', () => closeModal(loadModal));
saveConfirmBtn.addEventListener('click', confirmSave);
saveCancelBtn.addEventListener('click', () => closeModal(saveModal));

// 点击模态框外部关闭
window.addEventListener('click', function(e) {
    if (e.target === saveModal) {
        closeModal(saveModal);
    }
    if (e.target === loadModal) {
        closeModal(loadModal);
    }
});

// 保存图表名称输入框回车事件
chartNameInput.addEventListener('keypress', function(e) {
    if (e.key === 'Enter') {
        confirmSave();
    }
});

// 预览区域交互事件
previewContent.addEventListener('wheel', handleWheel);
previewContent.addEventListener('mousedown', handleMouseDown);
document.addEventListener('mousemove', handleMouseMove);
document.addEventListener('mouseup', handleMouseUp);

// 页面关闭前保存当前状态
window.addEventListener('beforeunload', function() {
    chartManager.saveLastChart();
});

// 初始化
function initialize() {
    // 初始化面板尺寸
    resetPanelSizes();
    
    // 尝试加载最后编辑的图表
    if (!chartManager.loadLastChart()) {
        // 如果没有历史记录，使用默认内容
        updateCurrentChartDisplay();
    }
    
    updateCharCount();
    renderDiagram();
}

// 启动应用
initialize(); 